<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="name">
        <el-input
          v-model="queryParams.key"
          placeholder="请输入任意检索值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:brand:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:brand:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:brand:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:brand:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="品牌id" align="center" prop="id"/>
      <el-table-column label="品牌名" align="center" prop="name"/>
      <el-table-column label="品牌logo" align="center" prop="logo">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="scope.row.logo" alt="" style="width: 150px;height: 150px">
            <img slot="reference" :src="scope.row.logo" style="width: 30px;height: 30px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" prop="status"/>
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="检索首字母" align="center" prop="firstLetter"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="associationCategory(scope.row)"
          >关联分类
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:brand:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:brand:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="品牌名" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名"/>
        </el-form-item>
        <el-form-item label="品牌logo" prop="logo">
          <el-input v-model="form.logo" type="textarea" placeholder="请输入内容"/>
          <!--          <el-upload-->
          <!--            class="upload-demo"-->
          <!--            action="https://jsonplaceholder.typicode.com/posts/"-->
          <!--            :on-preview="handlePreview"-->
          <!--            :on-remove="handleRemove"-->
          <!--            :file-list="fileList"-->
          <!--            list-type="picture">-->
          <!--            <el-button size="small" type="primary">点击上传</el-button>-->
          <!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          <!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态"/>
        </el-form-item>
        <el-form-item label="检索首字母" prop="firstLetter">
          <el-input v-model="form.firstLetter" placeholder="请输入检索首字母"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="关联分类" :visible.sync="dialogFormVisible" width="700px">
      <el-popover
        placement="right"
        width="400"
        trigger="click"
        v-model="visible">
        <el-cascader
          filterable
          clearable
          v-model="values"
          :options="categoryList"
          :props="props"
          @change="handleChange">
        </el-cascader>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="addCatelogSelect">确定</el-button>
        </div>
        <el-button slot="reference">新增分类</el-button>
      </el-popover>
      <el-table :data="association">
        <el-table-column property="id" label="id" width="150"></el-table-column>
        <el-table-column property="categoryName" label="分类名称" width="200"></el-table-column>
        <el-table-column property="brandName" label="品牌名称"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="delRelation(scope.row)"
            >移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listBrand, getBrand, delBrand, addBrand, brandChangeStatus, updateBrand} from "@/api/product/brand";
import {listCategory} from "@/api/product/category";
import {
  getBrandCategoryRelation,
  addBrandCategoryRelation,
  delBrandCategoryRelation
} from "@/api/product/brandCategoryRelation"

export default {
  name: "Brand",
  data() {
    return {
      //上传组件
      fileList: [],
      //级联选择器数据格式重写
      props: {
        value: "id",
        label: "label",
        children: "children"
      },
      //级联选择器  当前选中的值
      values: [],
      //级联选择器 分类数据
      categoryList: [],
      dialogFormVisible: false,
      association: [],

      //选中的品牌id
      brandId: '',

      //控制新增分类弹窗
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        logo: null,
        status: null,
        firstLetter: null,
        sort: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    //移除关联关系
    delRelation(row) {
      delBrandCategoryRelation(row.id).then(res => {
        this.$modal.msgSuccess("删除关联关系成功")
        this.getListRelation()
      })

    },
    popCatelogSelectVisible() {

    },
    addCatelogSelect() {
      //新增关联关系
      // this.values
      // this.brandId
      let categoryId = this.values[this.values.length - 1]
      let data = {"brandId": this.brandId, "categoryId": categoryId}
      addBrandCategoryRelation(data).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.visible = false
        this.getListRelation();
      });
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryList = response.data;
      });
    },
    //级联选择事件
    handleChange() {
      this.form.categoryId = value[value.length - 1]
      console.log(value);
    },
    //关联分类
    associationCategory(row) {
      this.dialogFormVisible = true;
      this.brandId = row.id
      this.getListRelation();
    },
    //获取关联分类信息
    getListRelation() {
      getBrandCategoryRelation(this.brandId).then(res => {
        this.association = res.rows
      })
    },
    // 状态修改
    handleStatusChange(row) {
      console.log(row)
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"用户吗？').then(function () {
        return brandChangeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 查询品牌列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        logo: null,
        status: 0,
        firstLetter: null,
        sort: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBrand(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改品牌";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBrand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除品牌编号为"' + ids + '"的数据项？').then(function () {
        return delBrand(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/brand/export', {
        ...this.queryParams
      }, `brand_${new Date().getTime()}.xlsx`)
    },

    //上传组件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    }
  }
};
</script>
